package net.j4love.nio.channels;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;

/**
 * @author he peng
 * @create 2018/5/4 17:40
 * @see Channels
 */
public class ChannelsTest {

    @Test
    public void newReadableChannel() throws Exception {
        InputStream in = new ByteArrayInputStream("hello NIO!".getBytes());

        // ReadableByteChannel 接口只负责读取数据
        ReadableByteChannel readableByteChannel = Channels.newChannel(in);
        ByteBuffer dstBuff = ByteBuffer.allocateDirect(10);
        byte[] buf = new byte[512];
        int size;
        while ((size = readableByteChannel.read(dstBuff)) != -1) {
            dstBuff.flip();
            dstBuff.get(buf , 0 , size);
            System.out.println(new String(buf , Charset.forName("utf-8")));
            dstBuff.flip();
        }
    }

    @Test
    public void newWritableChannel() throws Exception {
        WritableByteChannel writableByteChannel = Channels.newChannel(System.out);
        ByteBuffer buff = ByteBuffer.allocate(100);
        buff.put("nio is non-blocking io".getBytes());
        buff.flip();
        writableByteChannel.write(buff);
    }

}
